import os
from pathlib import Path
import time
import calendar
import json
import random
import re
# class server_FileIo:/Users/edy/Desktop/fastapmac/fastapmac
#     paht = "/Users/edy/Desktop/fastapmac/aadd"
    
import os
 
 
def is_file_empty(file_path):
    return os.path.getsize(file_path) == 0

#MARK: 这里是保存数据到文件
def save_FileIo(uuid):
        
     
        rand_int = random.randint(1, 1000)
        stringRand = str(rand_int)
        a = uuid
        c = get_timestamp() + stringRand
        b = {'times':c,'uuis':a}
        try:
           with open('example.txt', 'a') as file:
               file_path = 'example.txt'
               if is_file_empty(file_path):
                     print("文件为空")
                     file.write(set_jsonDic(b))
               else:
                     print("文件不为空")
                     file.write('\n'+ set_jsonDic(b))
               return c
        except FileNotFoundError:
           with open('example.txt', 'w') as file:
               file_path = 'example.txt'
               if is_file_empty(file_path):
                     print("文件为空")
                     file.write(set_jsonDic(b))
               else:
                     print("文件不为空")
                     file.write('\n'+ set_jsonDic(b))
               return c

             

#MARK: 这里是获取数据到文件
def get_FileIo(name):
    with open('example.txt', 'r') as file:
     for line in file:
        line = line.strip()  # 去除行尾的换行符
        print(line)
        if line and line[0] != '':
          d = get_jsonDic(line)
          print(d)
          strName = str(name)
          if d['times'] == strName:
               line
               print(d)
               delete_text('example.txt', line)

               return d['uuis']
        
     return "没有找到"
            

#MARK: 这里是删除文件中的内容
def delete_text(file_path, target_text):
    with open(file_path, 'r+') as f:
        content = f.read()
        modified_content = content.replace(target_text, '')  # 替换为空字符串[1,2](@ref)
        f.seek(0)  # 重置指针到文件开头
        f.write(modified_content)
        f.truncate()


#MARK: 这里是获取时间戳
def get_timestamp():
     timestamp = calendar.timegm(time.gmtime())
     timeString = time.time()
     stringTime = str(int(timeString))
     return stringTime
#MARK: 这里是字典生成json
def set_jsonDic(dic):
     json_data = json.dumps(dic)
     print(json_data)
     return json_data
#MARK: 这里是json生成字典
def get_jsonDic(strJson):
     # decoder = json.JSONDecoder()
     # dict_obj = decoder.decode(strJson)
     json_data = json.loads(strJson)
     print(json_data)
     return json_data


# MARK: 不能有空格
def isContent(boStr):
     # 匹配不包含空格的字符串
     pattern = re.compile(r'[^ ]+')
  
     # 查找匹配项
     match = pattern.match(boStr)
     if match:
          print("Found a match:", match.group())
          return True
     else:
          print("No match found")
          return False
